<?php

namespace App\Admin\Controllers;

use App\Models\DownloadRecord;

use App\Models\File;
use App\Models\Resource;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class DownloadRecordController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('下载记录');
//            $content->description('description');

            $content->body($this->grid());
        });
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(DownloadRecord::class, function (Grid $grid) {

            $grid->model()->orderBy('id', 'desc');
            $grid->model()->where('is_pay', 'finish');
            $grid->disableCreation();
            $grid->disableActions();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->id('ID')->sortable();
            $grid->model()->with('file');


            $grid->column('file_title', '资源名称')->display(function ($value) {
                if ($this->file)
                    return $this->file['title'];

                return $value;
            });

            $grid->column('pay_amount', '付费金额(金币)');

            $grid->column('category', '资源类型')->display(function ($value) {
                if ($this->file)
                    return $this->file['category'];
            });

            $grid->created_at('下载时间');
            $grid->column('user_id', '用户名')->display(function ($value) {
                $user = User::select('id', 'name')->find($value);

                if (!$user)
                    return '用户不存在';

                return '<a href="' . admin_base_path('user/' . $value) . '" target="_blank">'. $user->name .'</a>';
            });
//            $grid->updated_at();

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->like('file_title', '资源名称');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('user', function ($q) use ($input) {
                        $q->where('name', 'like', '%' . $input . '%');
                        $q->select('users.id', 'name');
                    });
                }, '用户名');
                $filter->like('user_id','用户的ID');
                $filter->between('created_at', '下载时间')->datetime();
            });
        });
    }
}
